package com.example.dreamlist2.todo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.dreamlist2.CalendarUtils;
import com.example.dreamlist2.R;
import com.example.dreamlist2.StateInfo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class TodoAddActivity extends AppCompatActivity {

    LinearLayout add_time, add_date, add_type, add_cancle, add_commit;
    Switch switch_alert, switch_done;
    EditText etitle, econtent;
    TextView show_date, show_time, show_type;
    String title, content, type = "未定义";
    Date date;
    Integer done, Year, Month, Day, Hour, Minute;
    TodoItem todoItem;
    private AlertDialog alertDialog; //单选框

    StateInfo stateInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.todo_add);

        add_time = findViewById(R.id.add_time);
        add_date = findViewById(R.id.add_date);
        add_type = findViewById(R.id.add_type);
        add_cancle = findViewById(R.id.add_cancle);
        add_commit = findViewById(R.id.add_commit);
        switch_alert = findViewById(R.id.switch_alert);
        switch_done = findViewById(R.id.switch_done);
        show_date = findViewById(R.id.show_date);
        show_time = findViewById(R.id.show_time);
        show_type = findViewById(R.id.show_type);
        etitle = findViewById(R.id.edit_todo_title);
        econtent = findViewById(R.id.edit_todo);

        todoItem = new TodoItem();

        stateInfo = (StateInfo)getApplication();
        Calendar mcalendar = Calendar.getInstance();     //  获取当前时间    —   年、月、日
        Year = mcalendar.get(Calendar.YEAR);         //  得到当前年
        Month = mcalendar.get(Calendar.MONTH);       //  得到当前月
        Day = mcalendar.get(Calendar.DAY_OF_MONTH);  //  得到当前日
        Hour  = mcalendar.get(Calendar.HOUR_OF_DAY);    //得到小时
        Minute  = mcalendar.get(Calendar.MINUTE);            //得到分钟
        //todo:选择时间控件
        add_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int hour  = Hour;    //得到小时
                int min  = Minute;            //得到分钟
                new TimePickerDialog(TodoAddActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        // 得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                        Hour = hourOfDay;
                        Minute = minute;
                        show_time.setText(""+Hour+":"+Minute);
                    }
                }, hour, min, true).show();
            }
        });

        //todo:选择日期控件
        add_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int year = Year;         //  得到当前年
                int month = Month;       //  得到当前月
                int day = Day;  //  得到当前日

                new DatePickerDialog(TodoAddActivity.this, new DatePickerDialog.OnDateSetListener() { //  日期选择对话框
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        //得到选择后的 年，月，日，分别对应着三个参数 — year、month、dayOfMonth
                        Year = year;
                        Month = month + 1;
                        Day = dayOfMonth;
                        show_date.setText(""+Year+"-"+Month+"-"+Day);
                        Month = Month - 1;
                    }
                },year,month,day).show();   //  弹出日历对话框时，默认显示 年，月，日
            }
        });

        //todo:选择类别控件
        add_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSingleAlertDialog(v);
            }
        });

        //取消并返回
        add_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(1);
                TodoAddActivity.this.finish();
            }
        });

        //确认并提交
        //todo:上传数据库
        add_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title = etitle.getText().toString();
                content = econtent.getText().toString();
                if(switch_done.isChecked()){
                    done = 1;
                }
                else{
                    done = 0;
                }
                if(switch_alert.isChecked() && done == 0){
                    register_alert();
                }
                submit_todo();
            }
        });
    }

    //todo:注册提醒事件
    private void register_alert(){
        long begin_time = CalendarUtils.remindTimeCalculator(Year,Month, Day, Hour, Minute);
        long end_time = CalendarUtils.remindTimeCalculator(Year, Month, Day+1, Hour, Minute);
        CalendarUtils.onCalendarRemindListener callback = null;
        CalendarUtils.addCalendarEventRemind(TodoAddActivity.this, title, content, begin_time, end_time, 0, callback);
    }

    //弹出类别选择框
    public void showSingleAlertDialog(View view) {
        final String[] items = {"未定义", "工作", "学习", "生活", "社交", "其他"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(TodoAddActivity.this);
        alertBuilder.setTitle("选择类别");
        alertBuilder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                type = items[i];
                Toast.makeText(TodoAddActivity.this, items[i], Toast.LENGTH_SHORT).show();
            }
        });

        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                show_type.setText(type);
                alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog.dismiss();
            }
        });
        alertDialog = alertBuilder.create();
        alertDialog.show();
    }

    //上传信息至数据库
    private void submit_todo(){
        todoItem.setTitle(title);
        todoItem.setContent(content);
        todoItem.setF_done(done);
        todoItem.setType(type);
        todoItem.setUid(stateInfo.getUserin().getObjectId());
        date = new Date();
        Month = Month + 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start_time = Year.toString()+"-"+Month.toString()+"-"+Day.toString()+" "
                +Hour.toString()+":"+Minute.toString()+":00";
        try {
            date = sdf.parse(start_time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        BmobDate bdate = new BmobDate(date);
        todoItem.setDate(bdate);

        todoItem.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if(e==null){
                    Log.i("bmob","新建todo成功");
                    Toast.makeText(TodoAddActivity.this, "添加成功！", Toast.LENGTH_SHORT);
                    setResult(1);
                    finish();
                }else{
                    Log.i("bmob","新建todo失败："+e.getMessage()+","+e.getErrorCode());
                    Toast.makeText(TodoAddActivity.this, "添加失败……", Toast.LENGTH_SHORT);
                }
            }
        });
    }
}